package com.etlmaster.executor.steps.func;

import javax.script.Bindings;
import javax.script.Compilable;
import javax.script.CompiledScript;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

import com.etlmaster.executor.StepMeta;
import com.etlmaster.executor.annotation.StepInstruction;
import com.etlmaster.executor.utils.StepState;

/**
 * @author Wugf
 * @date 2016-03-08
 */
@StepInstruction("js")
public class JavaScriptStep extends FuncStep {
	
	
	private JavaScriptStepMeta meta;

	public JavaScriptStep(StepMeta meta) {
		super(meta);
		this.meta = (JavaScriptStepMeta) meta;
	}

	@Override
	protected int handle() {
		ScriptEngineManager sem = new ScriptEngineManager();
		ScriptEngine engine = null;
	    try{
	    	engine = sem.getEngineByName("nashorn");
	    	if(engine==null){
	    		meta.log("DEBUG","创建nashorn引擎失败，未使用Jdk 8，使用默认Rhino引擎");
		    	engine = sem.getEngineByName("JavaScript");
	    	}
	    }catch(Exception e){
	    	meta.log("DEBUG","创建nashorn引擎失败，不是使用Jdk 8使用默认Rhino引擎，{}",e.getMessage());
	    	engine = sem.getEngineByName("JavaScript");
	    }
	    Compilable compilable = (Compilable) engine;
		try {
			Bindings bindings = engine.createBindings();
			CompiledScript jsFunc1 = compilable.compile(meta.getScript());
			bindings.put("meta", meta);
			bindings.put("step", this);
			Object obj = jsFunc1.eval(bindings);
		} catch (ScriptException e) {
			meta.log("INFO","执行JS脚本报错，{}",e.getMessage());
			return StepState.RUNNING_FAILED;
		}
		return StepState.RUNNING_SUCCESSED;
	}
	
	public void log(String text,Object... args){
		String []logs=new String[args.length+2];
		logs[0]="INFO";
		logs[1]=text;
		for(int i=0;i<args.length;i++){
			logs[i+2]=(String) args[i];
		}
		meta.log( logs);
	}

	@Override
	public boolean stop() {
		return false;
	}
}
